package com.kecheng.com.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kecheng.pojo.Admin;

public class LoginFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("destroy");
	}

	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession(true);

		Admin admin = (Admin) session.getAttribute("admin");
		
		String resUrl = req.getRequestURL().toString();
		// 判断如果没有取到用户信息,就跳转到登陆页面
		boolean flag = false;
		if(resUrl.contains(".action")){
			//通过action访问的方法，可能有前端的，所以判断下是不是后端的
			if(resUrl.contains("admin/")&&!(resUrl.contains("login")))flag = true;
		}else{
			//直接访问页面的方式，这里只有admin下面的文件才会进这里噢，判断是否是页面
			if(resUrl.contains(".jsp")&&!(resUrl.contains("login")))flag = true;
		}
		if (flag&&admin==null) {
			// 跳转到登陆页面
			res.sendRedirect("http://" + req.getHeader("Host")+"/admin/login.jsp");
			//res.sendRedirect("https://www.baidu.com/?tn=39042058_12_oem_dg");
		} else {
			// 已经登陆,继续此次请求
			chain.doFilter(request,response);
		}
	}

	public void init(FilterConfig config) throws ServletException {
		
	}

}
